﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace os
{
    // 订单明细类
    public class OrderDetails
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; } // 商品数量

        // 添加无参构造函数
        public OrderDetails() { }

        public OrderDetails(int id, string productName, double price, int quantity)
        {
            Id = id;
            ProductName = productName;
            Price = price;
            Quantity = quantity;
        }

        public override bool Equals(object obj)
        {
            return obj is OrderDetails details &&
                   Id == details.Id &&
                   ProductName == details.ProductName &&
                   Price == details.Price &&
                   Quantity == details.Quantity;
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Id, ProductName, Price, Quantity);
        } // 是.NET 提供的一个静态方法，其用途是把多个值组合成一个哈希码。该方法会对传入的每个值进行哈希计算，接着将这些哈希值组合成一个新的哈希码。

        public override string ToString()
        {
            return $"订单明细 ID: {Id}, 商品名称: {ProductName}, 单价: {Price}, 数量: {Quantity}";
        }
    }

    // 订单类
    public class Order
    {
        public int OrderId { get; set; }
        public string Customer { get; set; }
        public List<OrderDetails> OrderDetailsList { get; set; }
        public double TotalAmount => OrderDetailsList.Sum(d => d.Price * d.Quantity); // 在 Lambda 表达式里，使用单个字母（像 d、x、i 等）作为参数名是一种常见的做法，程序员们能快速理解它代表列表中的一个元素。

        // 添加无参构造函数
        public Order() { }

        public Order(int orderId, string customer, List<OrderDetails> orderDetailsList)
        {
            OrderId = orderId;
            Customer = customer;
            OrderDetailsList = orderDetailsList;
        }

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId &&
                   Customer == order.Customer &&
                   OrderDetailsList.SequenceEqual(order.OrderDetailsList);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(OrderId, Customer, OrderDetailsList);
        }

        public override string ToString()
        {
            string details = string.Join(Environment.NewLine, OrderDetailsList.Select(d => $"  {d}"));
            return $"订单 ID: {OrderId}, 客户: {Customer}, 总金额: {TotalAmount}{Environment.NewLine}{details}";
        }
    } // 同样，这里的 d 代表 OrderDetailsList 列表中的每一个 OrderDetails 对象。选择 d 作为参数名也是基于上述简洁性、约定俗成和局部性的考虑。

    // 订单服务类
    public class OrderService
    {
        private List<Order> orders = new List<Order>();

        public void AddOrder(Order order)
        {
            if (orders.Contains(order))
            {
                throw new Exception("该订单已存在，不能重复添加。");
            }
            orders.Add(order);
        }

        public void DeleteOrder(int orderId)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
            {
                throw new Exception($"未找到订单号为 {orderId} 的订单，删除失败。");
            }
            orders.Remove(order);
        }

        public void ModifyOrder(Order newOrder)
        {
            var oldOrder = orders.FirstOrDefault(o => o.OrderId == newOrder.OrderId);
            if (oldOrder == null)
            {
                throw new Exception($"未找到订单号为 {newOrder.OrderId} 的订单，修改失败。");
            }
            orders.Remove(oldOrder);
            orders.Add(newOrder);
        }

        public List<Order> QueryOrders(Func<Order, bool> condition)
        {
            return orders.Where(condition).OrderBy(o => o.TotalAmount).ToList();
        }
        // 在 QueryOrders 方法里，orders.Where(condition) 这部分代码使用了 LINQ（Language Integrated Query）的 Where 方法。Where 方法接受一个 Func<TSource, bool> 类型的委托作为参数，用于筛选集合中的元素。具体来说，Where 方法会对 orders 列表中的每个 Order 对象调用 condition 委托所封装的方法，如果该方法返回 true，则该 Order 对象会被包含在筛选结果中；如果返回 false，则会被排除。
        // OrderBy(o => o.TotalAmount) 会对筛选后的结果按照 Order 对象的 TotalAmount 属性进行升序排序，最后 ToList() 方法将排序后的结果转换为一个 List<Order> 列表并返回。
        public void SortOrders()
        {
            orders = orders.OrderBy(o => o.OrderId).ToList();
        }

        public void SortOrders(Func<Order, object> keySelector)
        {
            orders = orders.OrderBy(keySelector).ToList();
        }

        // 导出订单到 XML 文件
        public void Export(string filePath)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    serializer.Serialize(writer, orders);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"导出订单时发生错误: {ex.Message}");
            }
        }

        // 从 XML 文件中导入订单
        public void Import(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                        orders = (List<Order>)serializer.Deserialize(reader);
                    }
                }
                else
                {
                    Console.WriteLine($"文件 {filePath} 不存在。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"导入订单时发生错误: {ex.Message}");
            }
        }

        // 新增方法：显示所有订单信息
        public void DisplayAllOrders()
        {
            if (orders.Count == 0)
            {
                Console.WriteLine("当前没有订单信息。");
            }
            else
            {
                Console.WriteLine("所有订单信息：");
                foreach (var order in orders)
                {
                    Console.WriteLine(order);
                }
            }
        }
    }

    class Program
    {
        static void Main()
        {
            OrderService orderService = new OrderService();

            // 添加订单
            try
            {
                var orderDetails1 = new List<OrderDetails>
            {
                new OrderDetails(1, "iphone", 5000, 1),
                new OrderDetails(2, "耳机", 500, 2)
            };
                var order1 = new Order(1, "张三", orderDetails1);
                orderService.AddOrder(order1);

                var orderDetails2 = new List<OrderDetails>
            {
                new OrderDetails(3, "电视", 8000, 1),
                new OrderDetails(4, "背包", 200, 1)
            };
                var order2 = new Order(2, "李四", orderDetails2);
                orderService.AddOrder(order2);

                Console.WriteLine("添加订单后：");
                orderService.DisplayAllOrders();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // 删除订单
            try
            {
                orderService.DeleteOrder(1);
                Console.WriteLine("\n删除订单 1 后：");
                orderService.DisplayAllOrders();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // 修改订单
            try
            {
                var newOrderDetails = new List<OrderDetails>
            {
                new OrderDetails(3, "电视", 8500, 1),
                new OrderDetails(4, "背包", 250, 1)
            };
                var newOrder = new Order(2, "李四", newOrderDetails);
                orderService.ModifyOrder(newOrder);
                Console.WriteLine("\n修改订单 2 后：");
                orderService.DisplayAllOrders();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // 查询订单
            var queryResult = orderService.QueryOrders(o => o.Customer == "李四");
            Console.WriteLine("\n查询客户为李四的订单：");
            foreach (var order in queryResult)
            {
                Console.WriteLine(order);
            }

            // 排序订单（按 OrderId）
            orderService.SortOrders();
            Console.WriteLine("\n按 OrderId 排序后：");
            orderService.DisplayAllOrders();

            // 排序订单（按 TotalAmount）
            orderService.SortOrders(o => o.TotalAmount);
            Console.WriteLine("\n按 TotalAmount 排序后：");
            orderService.DisplayAllOrders();

            // 导出订单到 XML 文件
            orderService.Export("D:/ruangou/orders.xml");
            Console.WriteLine("\n订单已导出到 D:/ruangou/orders.xml");

            // 清空订单列表
            orderService = new OrderService();
            Console.WriteLine("\n清空订单列表后：");
            orderService.DisplayAllOrders();

            // 从 XML 文件中导入订单
            orderService.Import("D:/ruangou/orders.xml");
            Console.WriteLine("\n从 XML 文件导入订单后：");
            orderService.DisplayAllOrders();
        }
    }
}
